//
//  CarInfoViewController.m
//  JiongTu
//
//  Created by Dupengfei on 16/4/22.
//  Copyright © 2016年 YSKJ. All rights reserved.
//

#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

#import "CarInfoViewController.h"
#import <AVFile.h>
#import <AVObject.h>
#import <SVProgressHUD.h>
#import <AVUser.h>
#import <AVQuery.h>
#import "KindOfCarViewController.h"
#import "JTUser.h"
#import <AVOSCloud.h>
@interface CarInfoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UITextField *location;
/**
 *  行驶证号码
 */
@property (weak, nonatomic) IBOutlet UITextField *driving_licenseId;
/**
 *  车牌号码
 */
@property (weak, nonatomic) IBOutlet UITextField *licence_plate;
/**
 *  车型
 */
@property (weak, nonatomic) IBOutlet UITextField *vehicle_model;


@property (weak, nonatomic) IBOutlet UIButton *driverCard;

@property (weak, nonatomic) IBOutlet UIButton *driverCard1;
@property (weak, nonatomic) IBOutlet UIButton *drivingCard;

@property (weak, nonatomic) IBOutlet UIButton *button;
@property (nonatomic, strong) NSData * data;
@property (nonatomic, assign)int number;
@property (nonatomic, strong) UIPickerView * pickerView;
@property (nonatomic, strong)NSArray * locationArray;
@property (nonatomic, strong)AVObject * driver;
@end

@implementation CarInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self initializeDateSource];
    self.title =@"实车认证";
    _location.text =@"A";
    self.vehicle_model.delegate =self;
    self.driving_licenseId.delegate = self;
    self.licence_plate.delegate = self;
    
    self.driving_licenseId.keyboardType = UIKeyboardTypeASCIICapable;
    
    _location.inputView =self.pickerView;
    
    _licence_plate.keyboardType= UIKeyboardTypeAlphabet;
    _driving_licenseId.keyboardType =UIKeyboardTypeAlphabet;
       [ _licence_plate addTarget:self action:@selector(nameTextField:) forControlEvents:UIControlEventEditingChanged];
     [ _driving_licenseId addTarget:self action:@selector(driverTextField:) forControlEvents:UIControlEventEditingChanged];
}

- (void)nameTextField:(UITextField *)textField
{
    if (textField.text.length >5) {
        [SVProgressHUD showErrorWithStatus:@"您最多输入5位！"];
        textField.text = [textField.text substringToIndex:5];
    }
}
- (void)driverTextField:(UITextField *)textField
{
    if (textField.text.length >17) {
        [SVProgressHUD showErrorWithStatus:@"您最多输入17位！"];
        textField.text = [textField.text substringToIndex:17];
    }
}



-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.vehicle_model.text =[[NSUserDefaults standardUserDefaults]objectForKey:@"carName"];
    
    
}

-(void)initializeDateSource
{
    _locationArray =@[@"A",@"B",@"C",@"D",@"E",@"F",@"H",@"J",@"K",@"L",@"M",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
}

#pragma mark 按钮交互事件
//行驶证正面
- (IBAction)driverCardPressed:(UIButton *)sender {
    
    _number =0;
    
    [self takePhotoFromPhone];
}
//行驶证反面
- (IBAction)driverCard1Pressed:(UIButton *)sender {
    _number =1;
    [self takePhotoFromPhone];
}
//驾驶证正面照
- (IBAction)buttonPressed:(UIButton *)sender {
    _number =2;
    [self takePhotoFromPhone];
}

//完成按钮

- (IBAction)finishButtonPressed:(UIButton *)sender {
  
    
    if ([_driving_licenseId.text isEqualToString:@""]) {
        
        [SVProgressHUD showErrorWithStatus:@"行驶证号不能为空"];
    }
    else if ([_licence_plate.text isEqualToString:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"车牌号码不能为空"];
    }
    else if ([_vehicle_model.text isEqualToString:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"车型为空"];
    }
    else if (_driverCard.currentImage ==nil)
    {
        [SVProgressHUD showErrorWithStatus:@"照片不能为空"];
    }
    else if (_driverCard1.currentImage ==nil)
    {
        [SVProgressHUD showErrorWithStatus:@"照片不能为空"];
    }

    else if (_drivingCard.currentImage ==nil)
    {
        [SVProgressHUD showErrorWithStatus:@"照片不能为空"];
    }
    else if (_driving_licenseId.text.length<17)
    {
        [SVProgressHUD showErrorWithStatus:@"行驶证号码输入有误"];
    }
    else if (_licence_plate.text.length<5)
    {
        [SVProgressHUD showErrorWithStatus:@"车牌号码输入有误"];
    }

    else{
        
        [SVProgressHUD showWithStatus:@"正在上传，请耐心等待"];

        AVQuery * query =[AVQuery queryWithClassName:@"Driver"];
        [query whereKey:@"DriverId" equalTo:[AVUser currentUser].objectId];

        if ([query findObjects].count !=0) {
           _driver =[query findObjects][0];
        }
        else
        {
            _driver =[AVObject objectWithClassName:@"Driver"];
        }
        AVObject * car =[AVObject objectWithClassName:@"Car"];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:@"image.png"];
        AVFile *file = [AVFile fileWithName:@"image" contentsAtPath: imagePath];
        NSString *imagePath1 = [documentsDirectory stringByAppendingPathComponent:@"image1.png"];
        AVFile *file1 = [AVFile fileWithName:@"image1" contentsAtPath: imagePath1];
        NSString *imagePath2 = [documentsDirectory stringByAppendingPathComponent:@"image2.png"];
        AVFile *file2 = [AVFile fileWithName:@"image2" contentsAtPath: imagePath2];
        NSArray * imageArray =@[file1,file,file2];
        [file save];
        [file1 save];
        [file2 save];
        [car setObject:imageArray forKey:@"CarImage"];
        [car setObject:_driving_licenseId.text forKey:@"DriverNumber"];
        [car setObject:[NSString stringWithFormat:@"川%@",[_location.text stringByAppendingString:_licence_plate.text]] forKey:@"CarNumber"];
        [car setObject:_vehicle_model.text forKey:@"CarName"];
        [car save];
        [_driver setObject:car forKey:@"CarInfo"];
        [_driver setObject:[AVUser currentUser].objectId forKey:@"DriverId"];
        [_driver saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    
            if (succeeded) {
                
                [SVProgressHUD showSuccessWithStatus:@"提交成功，请耐心等待！"];
                
                NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
                [dict setObject:[JTUser currentUser].mobilePhoneNumber forKey:@"phoneNumber"];
//                [dict setObject:_driver.objectId forKey:@"objectId"];
                
                [AVOSCloud requestSmsCodeWithPhoneNumber:@"15982086828" templateName:@"Car" variables:dict callback:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                         [self.navigationController popViewControllerAnimated:YES];
                    } else {
                        NSLog(@"%@", error);
                    }
                }];

                
               
                
            }
            
            
        }];
        
    }

    
}


#pragma mark delegate 选取照片协议
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        }];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    _data = UIImageJPEGRepresentation(image, 0.3);
   
    //这里将图片放在沙盒的documents文件夹中
    NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:_data attributes:nil];
    //得到选择后沙盒中图片的完整路径
    //   NSString * filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
    switch (_number) {
        case 0:
        {
            [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:_data attributes:nil];
            [self.driverCard setImage:image forState:UIControlStateNormal];
        }
            break;
        case 1:
        {
            [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image1.png"] contents:_data attributes:nil];
            [self.driverCard1 setImage:image forState:UIControlStateNormal];
        }
            break;
        case 2:
        {
            [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image2.png"] contents:_data attributes:nil];
            [self.drivingCard setImage:image forState:UIControlStateNormal];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark 读取现相机相册
-(void)takePhotoFromPhone
{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:@"请选择" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:^{
        }];
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:^{
        }];
    }];
    UIAlertAction * action2 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action];
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_driving_licenseId resignFirstResponder];
    [_licence_plate resignFirstResponder];
    [_vehicle_model resignFirstResponder];
    [_location resignFirstResponder];
}

#pragma mark-textfiled代理

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:self.vehicle_model]) {
        KindOfCarViewController * view =[[KindOfCarViewController alloc]init];
        [self.navigationController pushViewController:view animated:YES];
        return NO;
    } else {
        return YES;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    BOOL canChange = [string isEqualToString:filtered];
    return canChange;
}

#pragma mark-getter
-(UIPickerView *)pickerView
{
    if (!_pickerView) {
        _pickerView =[[UIPickerView alloc]init];
        _pickerView.delegate =self;
        _pickerView.dataSource =self;
    }
    return _pickerView;
}
#pragma mark-UIPickerViewDelegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return 21;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return _locationArray[row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    _location.text =_locationArray[row];
}
@end
